//
//  ColorExtension.swift
//  LXSwift_Example
//
//  Created by 广东万商通科技有限公司 on 2024/12/19.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import Foundation
import UIKit

 extension UIColor {
    
    /// 使用十六进制字符串初始化颜色
     public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
       
        var formatted = hexString.replacingOccurrences(of: "0x", with: "")
        formatted = formatted.replacingOccurrences(of: "#", with: "")
        
        if formatted.count == 6 {
            guard let rgbValue = UInt32(formatted, radix: 16) else { return nil }
            self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                      green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                      blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                      alpha: alpha)
            
        } else if formatted.count == 8 { // 支持包含 alpha 值的十六进制字符串 (e.g., #AARRGGBB)
            
            guard let argbValue = UInt32(formatted, radix: 16) else { return nil }
            self.init(red: CGFloat((argbValue & 0x00FF0000) >> 16) / 255.0,
                      green: CGFloat((argbValue & 0x0000FF00) >> 8) / 255.0,
                      blue: CGFloat(argbValue & 0x000000FF) / 255.0,
                      alpha: CGFloat((argbValue & 0xFF000000) >> 24) / 255.0)
            
        } else {
            return nil
        }
    }
    
    /// 使用 RGB 值初始化颜色
     public convenience init(r: Int, g: Int, b: Int, a: CGFloat = 1.0) {
        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a)
    }
    
    ///随机颜色
     public  static var random: UIColor {
        return UIColor(red: .random(in: 0...1),
                       green: .random(in: 0...1),
                       blue: .random(in: 0...1),
                       alpha: 1.0)
    }
}
